package com.turbo.cloud.gateway.utils;

import cn.hutool.core.util.StrUtil;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.util.List;
import java.util.Objects;

/**
 * Http 请求参数工具库
 * @author zhangluning
 */
public class RequestParamUtil {
    /**
     * 应用ID
     */
    private static final String X_APP_ID = "x-app-id";
    /**
     * 应用KEY
     */
    private static final String X_APP_KEY = "x-app-key";

    /**
     * 获取应用ID
     *
     * @param request 请求
     */
    public static String getXAppId(ServerHttpRequest request) {
        return getValue(request, X_APP_ID);
    }

    /**
     * 获取应用KEY
     *
     * @param request 请求
     */
    public static String getXAppKey(ServerHttpRequest request) {
        return  getValue(request, X_APP_KEY);
    }


    /**
     * 从请求中取值
     *
     * @param request 请求
     * @param key     参数key
     */
    private static String getValue(ServerHttpRequest request, String key) {
        // 先从params中获取，没有从header获取
        List<String> paramList = request.getQueryParams().get(key);
        List<String> headerList = request.getHeaders().get(key);
        if (Objects.nonNull(paramList) && paramList.size() > 0 && StrUtil.isNotEmpty(paramList.get(0))) {
            return paramList.get(0);
        } else if (Objects.nonNull(headerList) && headerList.size() > 0 && StrUtil.isNotEmpty(headerList.get(0))) {
            return headerList.get(0);
        } else {
            return null;
        }
    }
}
